package com.appistry.management.domain.impl;

import java.net.InetAddress;
import java.util.Map;

import org.json.JSONException;

import com.appistry.api.rest.domain.RestResponse;
import com.appistry.management.Service;
import com.appistry.management.ServiceApp;
import com.appistry.management.ServiceAppInfo;
import com.appistry.management.State;
import com.appistry.management.domain.AbstractRestDomainObject;
import com.appistry.management.domain.ControllerAction;
import com.appistry.management.exception.FabricManagerException;
import com.appistry.management.rest.RestFabricManager;
import com.appistry.management.util.JsonTransformUtil;

public class ServiceAppImpl extends AbstractRestDomainObject implements ServiceApp{
	private RestFabricManager restFabricManager;
	private String appName;
	private Service service;

	public ServiceAppImpl(RestFabricManager restFabricManager, Service service, String appName) {
		this.restFabricManager = restFabricManager;
		this.appName = appName;
		this.service = service;
	}

	public String getName() {
		return appName;
	}
	
	public Service getService(){
		return service;
	}

	public ServiceAppInfo getServiceAppInfo() throws FabricManagerException {
		try {
			RestResponse restResponse = restFabricManager.getServiceAppInfo(service.getName(), appName);
			checkForErrors(restResponse);

			ServiceAppInfo serviceAppInfo = JsonTransformUtil.toServiceAppInfo(restResponse.getBodyAsString());

			return serviceAppInfo;

		} catch (JSONException e) {
			throw new FabricManagerException(PARSE_JSON_ERR, e);
		} catch (Exception e) {
			throw new FabricManagerException(e);
		}
	}

	public void reboot() throws FabricManagerException {
		serviceAppController(ControllerAction.REBOOT);	
	}

	public void start() throws FabricManagerException {
		serviceAppController(ControllerAction.START);
	}

	public void stop() throws FabricManagerException {
		serviceAppController(ControllerAction.STOP);	
	}

	public Map<InetAddress, State> getState() throws FabricManagerException {
		try {
			RestResponse restResponse = restFabricManager.getServiceAppState(service.getName(), appName);
			checkForErrors(restResponse);

			Map<InetAddress, State> workerStateMap = JsonTransformUtil.toWorkerStateMap(restResponse.getBodyAsString());
			
			return workerStateMap;
		} catch (JSONException e) {
			throw new FabricManagerException(PARSE_JSON_ERR, e);
		} catch (Exception e) {
			throw new FabricManagerException(e);
		}
	}

	private boolean serviceAppController(ControllerAction action) throws FabricManagerException {
		try {
			RestResponse restResponse = restFabricManager.serviceAppController(service.getName(), appName, action);
			checkForErrors(restResponse);

			return true;
		} catch (Exception e) {
			throw new FabricManagerException(e);
		}
	}

}
